var httpUtils = require('../../utils/httpUtils.js');
var utils = require('../../utils/util.js');
var app = getApp();
var btnIsUsing = false;

Page({
  data: {
    detailData: {},
    picDatas: {},
    referenceImageBeforeStarting: [

    ],
    referenceImagesFromClient: [{
        id: '1',
        src: '../../images/reference_images_from_client_01.png'
      },
      {
        id: '2',
        src: '../../images/reference_images_from_client_02.png'
      },
      {
        id: '3',
        src: '../../images/reference_images_from_client_03.png'
      },
      {
        id: '4',
        src: '../../images/reference_images_from_client_04.png'
      },
      {
        id: '5',
        src: '../../images/reference_images_from_client_05.png'
      }
    ],
    referenceImagesFromClient: [{
        id: '1',
        src: '../../images/reference_images_from_client_01.png'
      },
      {
        id: '2',
        src: '../../images/reference_images_from_client_02.png'
      },
      {
        id: '3',
        src: '../../images/reference_images_from_client_03.png'
      },
      {
        id: '4',
        src: '../../images/reference_images_from_client_04.png'
      },
      {
        id: '5',
        src: '../../images/reference_images_from_client_05.png'
      }
    ],
    expressImage: [

    ],
    acceptanceCheckImageList: [

    ],
    currentTab: 1,
    clientHeight: 'auto',
    order_id: ''
  },
  onLoad: function(option) {
    var res = wx.getSystemInfoSync();
    var clientHeight = res.windowHeight * 2 + 'rpx';
    this.setData({
      clientHeight: clientHeight,
      order_id: option.order_id
    });
    var url = app.globalData.interfaceUrl + '/order.do?method=orderDetail';
    var _this = this;
    httpUtils.post(url, {
      'orderId': option.order_id
    }, function(res) {
      var detailData = res.data.data;
      console.log(detailData);
      //设置文件icon
      if (!utils.isNull(detailData) && !utils.isNull(detailData.files) && detailData.files.length > 0) {
        detailData.files.forEach(function(value, index) {
          if (value.v1.indexOf(".doc") != -1) {
            value.icon = '../../images/word-icon.png';
          }
          if (value.v1.indexOf(".pdf") != -1) {
            value.icon = '../../images/pdf-icon.png';
          }
          if (value.v1.indexOf(".xlsx") != -1) {
            value.icon = '../../images/excel-icon.png';
          }
        })
      }
      _this.setData({
        detailData: detailData
      });

    }, function(res) {
      console.log(res);
    });

  },
  stopTouchMove: function() {
    return false;
  },
  clickTab: function(e) {
    //切换页签的时候,要加上吧order_id带上
    var order_id = e.currentTarget.dataset.order_id;
    console.log('查看下...' + order_id);
    var current = e.currentTarget.dataset.current;
    if (current == '0') {
      var url = app.globalData.interfaceUrl + '/order.do?method=orderPicInfo';
      var _this = this;
      httpUtils.post(url, {
        'orderId': order_id
      }, function(res) {
        var picDatas = res.data.data;
        console.log(picDatas);
        _this.setData({
          picDatas: picDatas
        });

      });
    }
    if (current == '1') {
      console.log('点击了资料');
    }
    var res = wx.getSystemInfoSync();
    var clientHeight = res.windowHeight * 2 + 'rpx';
    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      this.setData({
        currentTab: e.target.dataset.current,
        clientHeight: clientHeight
      })
    }
  },
  addImages: function(event) {
    var _this = this;
    var items_code = event.currentTarget.dataset.items_code;
    console.log(event);
    var order_id = event.currentTarget.dataset.order_id;
    console.log('单号' + order_id);
    console.log('items_code是' + items_code);
    var picDatas = this.data.picDatas;
    //第一步，先获取oss需要的签证信息
    _this.getOssToken(order_id);
    wx.chooseImage({
      count: 3,
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有  
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有  
      success: function(res) {
        console.log('查看选了的文件');
        console.log(JSON.stringify(res));
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片  
        var tempFilePaths = res.tempFilePaths;
        console.log(tempFilePaths);
        var oss_policy_key = "oss_policy_key";
        var oss_policy_info = wx.getStorageSync(oss_policy_key);
        console.log(JSON.stringify(oss_policy_info));
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片  
        //启动上传等待中...  

        var uploadImgCount = tempFilePaths.length;

        for (var i = 0, h = tempFilePaths.length; i < h; i++) {
          console.log(tempFilePaths[i]);
          var fileName = utils.getFomcatNowTime() + utils.getFileSuffix(tempFilePaths[i]);
          var babyData = {
            'key': order_id + "/" + fileName,
            'policy': oss_policy_info.policy,
            'OSSAccessKeyId': oss_policy_info.OSSAccessKeyId,
            'success_action_status': '200', //让服务端返回200,不然，默认会返回204  
            'signature': oss_policy_info.signature
          }

          _this.uploadFileAli(babyData, tempFilePaths[i], uploadImgCount, i, picDatas, order_id, items_code);
        }
      }
    })
  },
  gotoMakeCall: function(e) {
    var tel = e.currentTarget.dataset.tel;
    var title = e.currentTarget.dataset.title;
    var content = e.currentTarget.dataset.content;
    wx.showModal({
      title: title,
      content: content,
      confirmText: '立即拨打',
      success: function(res) {
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: tel,
            success: function() {
              console.log("拨打电话成功！")
            },
            fail: function() {
              console.log("拨打电话失败！")
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    });
  },
  gotoInsurance: function(e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../insurance/insurance?id=' + id
    })
  },
  sign: function(e) {
    if (btnIsUsing == false) {
      btnIsUsing = true;
      var order_id = e.currentTarget.dataset.order_id;
      var _this = this;
      console.log('我就看看执行了几次')

      var url = app.globalData.interfaceUrl + '/order.do?method=sign';

      httpUtils.post(url, {
        'orderId': order_id
      }, function(res) {
        wx.showToast({
          title: '签到成功',
          icon: 'success',
          duration: 1000,
          mask: true,
          success: function() {
            _this.onLoad({
              order_id: order_id
            });
          }
        });
        btnIsUsing = false;
      }, function(res) {
        btnIsUsing = false;
        wx.showToast({
          title: res.data.message,
          icon: 'none',
          duration: 2000,
          mask: true
        });
      });
    }
  },
  startWork: function(e) {
    var order_id = e.currentTarget.dataset.order_id;
    var _this = this;

    var url = app.globalData.interfaceUrl + '/orderOperation.do?method=startWork';

    httpUtils.post(url, {
      'orderId': order_id
    }, function(res) {
      wx.showToast({
        title: '操作成功',
        icon: 'success',
        duration: 1000,
        mask: true,
        success: function() {
          _this.onLoad({
            order_id: order_id
          });
        }
      })
    });
  },
  accept: function(e) {
    var order_id = e.currentTarget.dataset.order_id;
    var _this = this;
    var url = app.globalData.interfaceUrl + '/orderOperation.do?method=applyAccept';
    httpUtils.post(url, {
      'orderId': order_id
    }, function(res) {
      wx.showToast({
        title: '操作成功',
        icon: 'success',
        duration: 1000,
        mask: true,
        success: function() {
          _this.onLoad({
            order_id: order_id
          });
        }
      })
    });
  },
  getOssToken: function(order_id) {
    var _this = this;
    console.log("getOssToken--------------------")

    var url = app.globalData.interfaceUrl + '/alibaba/getOssPolicyInfo.do';
    //写入参数  
    var params = {
      orderId: order_id
    }
    httpUtils.post(url, params, function(res) {
      //res就是我们请求接口返回的数据
      var policyBean = res.data.data;
      console.log('这就不好了吧')
      console.log(JSON.stringify(res));
      var oss_policy_info = {
        "policy": policyBean.policy,
        "OSSAccessKeyId": policyBean.accessid,
        "signature": policyBean.signature
      }
      wx.setStorageSync("oss_policy_key", oss_policy_info)

    }, function(res) {
      console.log('错误');
      console.log(JSON.stringify(res));
    })
  },
  uploadFileAli: function(babyData, filePath, uploadImgCount, i, picDatas, order_id, items_code) {
    var uploadPicUrl = app.globalData.interfaceUrl + "/orderOperation.do?method=uploadPic";
    console.log((i + 1) + "/" + uploadImgCount + "  [" + filePath + "]");
    var _this = this;
    wx.uploadFile({
      url: app.globalData.uploadUrl,
      formData: babyData,
      name: 'file',
      filePath: filePath,
      header: {
        'content-type': 'multipart/form-data'
      },
      success: function(res) {
        console.log("uploadFile success", res);
        if (res.statusCode == 200) {
          //表示上传成功(可以在阿里云服务器查看上传的图片)

          var fileUrl = app.globalData.uploadPreUrl + "/" + babyData.key;
          console.log("fileUrl:" + fileUrl)
          if (!utils.isNull(picDatas) && !utils.isNull(picDatas.orderPicInfoVoWrappers)) {
            //吧图片数据,传到服务器上
            httpUtils.post(uploadPicUrl, {
              'orderId': order_id,
              'itemsCode': items_code,
              'url': fileUrl,
              'fileName': utils.getFileNameFromUrl(fileUrl)
            }, function(res) {
              var picId = res.data.data;
              picDatas.orderPicInfoVoWrappers.forEach(function (value, i) {
                if (value.itemsCode == items_code) {
                  if (utils.isNull(value.orderPicInfoVos)) {
                    value.orderPicInfoVos = [];
                  }
                  value.orderPicInfoVos.push({
                    'url': fileUrl,
                    'picId':picId
                  });
                }
              })
              _this.setData({
                'picDatas': picDatas
              });
            });
          }
          wx.showToast({
            title: '上传成功',
            icon: 'success',
            duration: 2000
          })
        }
      },
      fail: function(res) {
        wx.showToast('上传图片失败');
      }
    })

  },
  previewImg: function(e) {
    var url = e.currentTarget.dataset.url;
    var urls = e.currentTarget.dataset.urls;
    if (!utils.isNull(urls)) {
      urls = urls.map(function(value) {
        return value.url;
      });
      utils.previewImg(url, urls);
    }
  },
  previewBeforeWorkImg: function(e) {
    var url = e.currentTarget.dataset.url;
    var urls = e.currentTarget.dataset.urls;
    if (!utils.isNull(urls)) {
      urls = urls.map(function(value) {
        return value.originFileUrl;
      });
      utils.previewImg(url, urls);
    }
  },

  notifyAccept: function(e) {
    //电话通知验收的号码
    var notifyTel = e.currentTarget.dataset.accept_tel;
    wx.makePhoneCall({
      phoneNumber: notifyTel,
    });
  },
  previewFile: function(e) {
    var url = e.currentTarget.dataset.url;
    console.log(url);
    utils.previewFile(url);
  },

  //删除图片
  delPic: function(e) {
    var picId = e.currentTarget.dataset.pic_id;
    var orderId = e.currentTarget.dataset.order_id;
    var _this = this;
    wx.showModal({
      title: '提示',
      content: '确定要删除此图片吗？',
      success: function(res) {
        if (res.confirm) {
          var url = app.globalData.interfaceUrl + '/order.do?method=delPic';
          httpUtils.post(url, {
            'orderId': orderId,
            'picId': picId
          }, function(res) {
            var picInfoUrl = app.globalData.interfaceUrl + '/order.do?method=orderPicInfo';
            httpUtils.post(picInfoUrl, {
              'orderId': orderId
            }, function(res) {
              var picDatas = res.data.data;
              console.log(picDatas);
              _this.setData({
                picDatas: picDatas
              });
            });
          });
        }
      }
    })
  },
  getRejectInfo: function(e) {
    var order_id = e.currentTarget.dataset.order_id;
    wx.navigateTo({
      url: '../dismissedSuggestions/dismissedSuggestions?order_id=' + order_id,
    })
  },
  copy: function(e) {
    var url = app.globalData.downdLoadUrl;
    utils.setClipboardData(url);
  }
})